/*********************************************************************
 * PrimeSearchThread.java created on Feb 26, 2010
 *
 * This file is part of Sure Tech Support Portal System. 
 * Copyright @ 2010 Sure Tech (HK) Limited. All rights reserved.
 * Sure Tech PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *********************************************************************/
package demo.concurrent.primefinder;

import java.math.BigInteger;
import java.util.logging.Logger;

/**
 * @Author: Mac Wang
 * @Date: Feb 26, 2010 11:36:57 AM 
 * @Email: mac@suretech.com.hk
 */

public class PrimeSearchThread implements Runnable {

	private long lowerBound;
	private long upperBound;
	private ConcurrentPrimeNumberSource numberSource;
		
	public PrimeSearchThread(BigInteger lowerBound, 
							BigInteger upperBound,
							ConcurrentPrimeNumberSource numberSource) 
	{
		this.lowerBound = lowerBound.longValue();
		this.upperBound = upperBound.longValue();
		this.numberSource = numberSource;
	}
	
	public void run() 
	{
		BigInteger lastSearchResult, searchResult= BigInteger.valueOf(lowerBound);		
		do			
		{
			lastSearchResult = searchResult;
			try
			{
				searchResult = PrimeUtil.findFirstPrime( lastSearchResult.longValue()+1, upperBound);
				if (searchResult!=null)
					numberSource.addResultToBuffer(searchResult);
				else break;				
			}
			catch (Throwable t)
			{
				Logger.getAnonymousLogger().severe("Method findPrime(int,int) resulted in a runtime error");
				t.printStackTrace(System.err);				
				//continue where search left off?
			}
		}while (searchResult!=lastSearchResult);
		
		numberSource.searchThreadCompleted();		
	}
}
